package com.grj.template.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.grj.template.boot.domain.Permission;
import com.grj.template.boot.domain.RolePermission;
import com.grj.template.boot.domain.User;
import com.grj.template.boot.domain.UserRole;
import com.grj.template.boot.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RolePermissionService rolePermissionService;

    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.eq(User::getStatus, "1");
        List<User> list = userService.list(queryWrapper);
        if (list.size() != 1) {
            throw new UsernameNotFoundException("用户名不存在或密码错误:"+this.getClass().getName());
        }
        User user = list.get(0);
        List<UserRole> userRoles = userRoleService.list(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getUserId, user.getUserId()));
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Long> permissionIds = rolePermissionService.list(Wrappers.lambdaQuery(RolePermission.class).in(RolePermission::getRoleId, roleIds)).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<String> permissionList = permissionService.list(Wrappers.lambdaQuery(Permission.class).in(Permission::getPermissionId, permissionIds)).stream().map(Permission::getPermissionCode).collect(Collectors.toList());
        List<GrantedAuthority> authorities = new ArrayList<>();
        permissionList.forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }
}
